import { createSlice } from "@reduxjs/toolkit";
let initialState = {
  title: "",
  description: "",
  body: "",
  tag: "",
  tags: [],
  errors: null,
};

export const articleSlice = createSlice({
  name: "article",
  initialState,
  reducers: {
    articleFiledUpdate: (state, action) => {
      const key = action.payload.key;
      const value = action.payload.value;
      state[key] = value;
    },
    articleAddTag: (state) => {
      const tags = state.tags.concat([state.tag]);
      return { ...state, tags, tag: "" };
    },
    articleRemoveTag: (state, action) => {
      const removeTag = action.payload;
      const filterTags = state.tags.filter((tag) => {
        return tag !== removeTag;
      });
      return { ...state, tags: filterTags };
    },
    articleResult: (state, action) => {
      state.errors = action.payload;
    },
    onUnload: () => {
      return { ...initialState };
    },
    ArticleBySlugResult: (state, action) => {
      return { ...state, ...action.payload };
    },
    ArticleDeleteResult: (state, action) => {
      state.errors = action.payload;
    },
    ArticleFavoriteResult: (state, action) => {
      return { ...state, ...action.payload };
    },
  },
});

export const {
  articleFiledUpdate,
  articleAddTag,
  articleRemoveTag,
  articleResult,
  onUnload,
  ArticleBySlugResult,
  ArticleDeleteResult,
  ArticleFavoriteResult,
} = articleSlice.actions;

export default articleSlice.reducer;
